import React, { useState } from 'react'
import { Button, Form, Input, message, Upload } from 'antd';
import eventBus from '../../../utils/eventBus';
import api from "../../../apis/user"
export default function userCenter() {
  let userInfo = JSON.parse(localStorage.userInfo)
  const initialValues = {//表单的初始值
    account: userInfo.account,
    userGroup: userInfo.role,
    upload: [{ thumbUrl: `http://jacklv.cn/images/${userInfo.imgUrl}`, uid: userInfo.imgUrl }]
  };
  const [loading, setLoading] = useState(false)
  const [fileList, setFileList] = React.useState(initialValues.upload);
  const onFinish = async (values) => {
    console.log(values);
    try {
      const { account, upload, userGroup } = values
      const params = {
        account, userGroup
      }
      const response = upload[0].response
      if (response) {
        if (response.code == 1) {
          params.imgUrl = response.data
        } else {
          message.error("头像上传失败")
          return
        }
      } else params.imgUrl = upload[0].uid
      setLoading(true)
      await api.saveUserInfo(params)
      setLoading(false)
      userInfo.imgUrl = params.imgUrl
      localStorage.setItem("userInfo", JSON.stringify(userInfo))
      eventBus.emit("syncUserInfo")
      message.success("用户更新成功")
    } catch (error) {
      console.log("error", error);
      setLoading(false)
    }
  };
 
  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    setFileList(e?.fileList || []);
    return e?.fileList;
  };
  return (
    <div className="login addAccount">
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        style={{
          maxWidth: 600,
        }}
        //初始化表单值
        initialValues={initialValues}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="账户名"
          name="account"
        >
          <Input disabled />
        </Form.Item>
        <Form.Item
          label="角色"
          name="userGroup"
        >
          <Input disabled />
        </Form.Item>
        <Form.Item
          name="upload"
          label="头像"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          rules={[
            {
              required: true,
              message: '请选择头像!',
            },
          ]}
        >
          <Upload name="avatar"
            action="http://jacklv.cn/users/uploadProfile"
            headers={{
              token: localStorage.token
            }}
            listType="picture-card">
            {!fileList.length && "选择图片"}
          </Upload>
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button loading={loading} type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
